<?php
namespace App\Http\Controllers\Admin;


use App\Models\UserAddressModel;
use App\Models\UserBillModel;
use App\Models\UserModel;
use App\Utils\PhpSpreadsheetUtil;
use App\Validates\Admin\UserValidate;

class UserController extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if(request()->ajax()){
            $page = request()->input("page", 1);
            if(request()->input("real_name")){
                $map[] = ['real_name','like',"%".request()->input("real_name")."%"];
            }
            if(request()->input("nickname")){
                $map[] = ['nickname','like',"%".request()->input("nickname")."%"];
            }
            if(request()->input("mobile")){
                $map[] = ['mobile','like',"%".request()->input("mobile")."%"];
            }
            if(request()->input("uid")){
                $map[] = ['uid','=',request()->input("uid")];
            }

            $list = UserModel::getUserList($this->pageSize,$page,$map);

            if($list['data']){
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['create_time'] = date("Y-m-d H:i", $v['create_time']);
                    $list['data'][$k]['last_time'] = date("Y-m-d H:i", $v['last_time']);
                    $list['data'][$k]['real_name'] = $v['real_name'] ? : "--";
                    $list['data'][$k]['nickname'] = $v['nickname'] ? emoji_decode($v['nickname']) : "--";
                    $list['data'][$k]['sex'] = getSex($v['sex']);
                }
            }
            return $this->rjson($list);
        }
        return view('admin/user/user/index');
    }

    /**
     * 显示创建资源表单页.
     */
    public function create()
    {
        $uid = request()->input('uid');
        if($uid){
            $res = UserModel::find($uid);
            $res['birthday'] = $res['birthday'] ? date("Y-m-d",$res['birthday']) : "";
            $res['nickname'] = $res['nickname'] ? emoji_decode($res['nickname']) : "--";
        }
        return view('admin/user/user/modify',['model'=>$res]);
    }

    /**
     * 添加编辑
     */
    public function edit()
    {
        try {
            $data = request()->post();

            /*$UserValidate = new UserValidate();
            if (!$UserValidate->scene('edit')->check($data)) {
                return $this->result('', 500, $UserValidate->getError());
            }*/

            $data['birthday'] = $data['birthday'] ? strtotime($data['birthday']) : time();

            $res = UserModel::editUser($data);
            return $this->result('',$res['code'],$res['msg']);

        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }

    /**
     * 余额、积分
     */
    public function balance()
    {
        $uid = request()->input('uid');
        if($uid){
            $res = UserModel::find($uid);
            $res['nickname'] = $res['nickname'] ? emoji_decode($res['nickname']) : "--";
        }
        return view('admin/user/user/balance',['model'=>$res]);
    }

    /**
     * 余额积分操作
     */
    public function update_balance()
    {
        try {
            $res = UserModel::edit_balance();
            if($res['code'] == 500) return $this->result($res, 500, $res['msg']);
            $ret = UserBillModel::operateBill($res['data']);
            return $this->result('',$ret['code'],$ret['msg']);
        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }

    /**
     * 详情
     */
    public function read()
    {
        $uid = request()->input('uid');
        $res = UserModel::find($uid);
        $ads = UserAddressModel::where(['is_default' => 1, 'uid' => $uid])->orderBy('create_time','desc')->first();
        if($ads) {
            $res['address'] = "收货人：".$ads['real_name']." 手机号：".$ads['mobile']." 邮编：".$ads['post_code']." 地址：".$ads['province']." ".$ads['city']." ".$ads['district']." ".$ads['detail'];
        }
        $res['nickname'] = $res['nickname'] ? emoji_decode($res['nickname']) : "--";
        return view('admin/user/user/details',['model'=>$res]);
    }

    /**
     * 积分明细
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function integralInfo()
    {
        $page = request()->input('page',1);
        $map['uid'] = request()->input('uid');
        $map['category'] = "integral";

        $list = UserBillModel::getBalanceList($this->pageSize,$page,$map);

        return $this->rjson($list);
    }

    /**
     * 余额明细
     * @param  [type] $uid [description]
     * @return [type]      [description]
    */
    public function balanceInfo()
    {
        $page = request()->input('page',1);
        $map['uid'] = request()->input('uid');
        $map['category'] = "balance";

        $list = UserBillModel::getBalanceList($this->pageSize,$page,$map);

        return $this->rjson($list);
    }

    /**
     * 删除指定资源
     */
    /*public function delete()
    {
        try {
            $uid = request()->input("uid", 0);
            if(!$uid) return $this->result("",500, '系统繁忙，请重试');
            $res = UserModel::destroy($uid);
            if($res) {
                return $this->result("", 200, '操作成功');
            }
            return $this->result("", 500, '操作失败');
        } catch (\Exception $e) {
            return $this->result("",500,$e->getMessage());
        }
    }*/

    /**
     * 会员导出
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function exportExcel()
    {
        try {
            $ids = substr(request()->input('ids'), 1);
            if($ids){
                $map[] = ['uid','in',$ids];
            }
            if(request()->input("real_name")){
                $map[] = ['real_name','like',"%".request()->input("real_name")."%"];
            }
            if(request()->input("nickname")){
                $map[] = ['nickname','like',"%".request()->input("nickname")."%"];
            }
            if(request()->input("mobile")){
                $map[] = ['mobile','like',"%".request()->input("mobile")."%"];
            }
            if(request()->input("uid")){
                $map[] = ['uid','=',request()->input("uid")];
            }

            $field = ['uid','real_name','nickname','mobile','sex','create_time'];

            $list = UserModel::where($map)->select($field)->orderBy('last_time',"desc")->get()->toArray();
            if($list){
                foreach ($list as $k => $v) {
                    $list[$k]['real_name'] = $v['real_name'] ? : "--";
                    $list[$k]['nickname'] = $v['nickname'] ? emoji_decode($v['nickname']) : "--";
                    $list[$k]['sex'] = getSex($v['sex']);
                    $list[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }

                $el = new PhpSpreadsheetUtil();
                $heads = ['UID','姓名','昵称','电话','性别','注册时间'];

                $path = "ExcelFile";
                $this->deldir($path);
                $res = $el->exportExcel(
                    $list,
                    $heads,
                    "",
                    [
                        "savePath" => $path,
                        "setWidth" => ['A'=>15, 'B'=>20, 'C'=>20, 'D'=>20, 'E'=>20, 'F'=>20],
                        "bold" => ["A1:F1"],
                    ]
                );

                if($res){
                    $json['code'] = 200;
                    $json['data'] = ["src"=>cache("ExcelFilePath"),'time'=>date("YmdHis",time())];
                    return response()->json($json);
                }
            }
            return false;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 删除导出旧文件
     * @param  [type] $val [description]
     * @return [type]      [description]
     */
    public function deldir($val)
    {
        //如果是目录则继续
        $path = public_path("uploads/{$val}/");
        if(is_dir($path)){
            $p = scandir($path);
            foreach($p as $val){
                if($val !="." && $val !=".."){
                    if(is_dir($path.$val)){
                        $this->deldir($path.$val.'/');
                        @rmdir($path.$val.'/');
                    }else{
                        unlink($path.$val);
                    }
                }
            }
        }
    }
}
